import React, { useEffect, useState } from 'react'
import useGetTableData from '@/hooks/useGetTableDataV2'
import SearchForm from '@/components/QsfCustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './TableColumns'
import { SupplierGreyFabricVO as ITableData } from './types'
import CustomTable from '@/components/QsfCustomTable'
import { useNavigate } from 'react-router-dom'
import { searchConfig } from './FormConfig'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import './index.less'
import useCachePage from '@/hooks/useCachePage'
import {
  getSupplierGreyFabricList,
  importExcelForCreate,
  exportSupplierGreyFabric,
  reportFinishedQuantity,
  editSupplierGreyFabric,
  misreportingFinishedQuantity,
  transferFabricStock,
  getTransferFabricStock,
  createSupplierGreyFabric,
} from '@/api/fabric'
import { exportNotification, getRecentMonths, importNotification } from '@/utils/util'
import PermissionButton from '@/components/PermissionButton'
import { ImportOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons'
import { Button, Empty, Form, Input, message, Modal, Select, Space, Spin } from 'antd'
import useModal from '@/hooks/useModal'
import useGetProDevSeason from '@/hooks/useGetProDevSeason'
import { applicationTypeEnum, IMPORT_FILE_ENUM, OperationLogType } from '@/constant'
import useViewLogs from '@/hooks/useViewLogs'
import LogsDrawer from '@/components/LogsDrawer'
import ImportFileModal from '@/components/ImportFileModal'
import { EditFormVertical } from '@/components/CustomForm'
import { useAppSelector } from '@/store/hooks'
import { IMenuItem } from '../FactoryOrder'
import { onValuesChange } from '@/utils/onValuesChange'
import useSearchFabric from '@/hooks/useSearchFabric'
const Index: React.FC = () => {
  const navigate = useNavigate()
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [operateItems, setoperateItems] = useState<IMenuItem[]>([])
  const [SupplierIds, setSupplierIds] = useState<any[]>([])
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const [form] = useForm()
  const [FormUpload] = useForm()
  const ProDevSeason = useGetProDevSeason()
  const { FabricOption, handleSearchFabric } = useSearchFabric('fabricCode')
  const [stockQty, setstockQty] = useState<{ baseFabricStockQty: number; colorFabricStockQty: number }>({
    baseFabricStockQty: 0,
    colorFabricStockQty: 0,
  })
  const { SupplierOption, setSupplierOption, handleSearchSupplier } = useSearchSupplier('supplierId')
  const {
    SupplierOption: SupplierOptionF,
    setSupplierOption: setSupplierOptionF,
    handleSearchSupplier: handleSearchSupplierF,
  } = useSearchSupplier('supplierCode')
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'id',
    OperationLogType.SUPPLIER_GERY_FABRIC,
  )
  const { setCachePage, getCachePage } = useCachePage()
  const defaultDateRange = getRecentMonths('YYYY-MM-DD HH:mm:ss')
  const [spinning, setspinning] = useState(false)
  const [importFileShow, setimportFileShow] = useState(false)
  const [uploadLoading, setuploadLoading] = useState(false)
  const reportModalGrey = useModal({
    onSuccess: () => {
      message.success('操作成功')
      reload()
    },
  })
  const transferModal = useModal({
    onSuccess: () => {
      message.success('操作成功')
      reload()
    },
  })
  const editModalGrey = useModal({
    onSuccess: () => {
      message.success('操作成功')
      reload()
    },
  })
  const addModal = useModal({
    onSuccess: () => {
      message.success('操作成功')
      reload()
    },
  })
  const { tableProps, params, search, reset, reload } = useGetTableData<ITableData>(getSupplierGreyFabricList, {
    form: form,
    immediatelySend: false,
    defaultFieldsParams: {
      createTimeStart: defaultDateRange,
    },
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
    paramsCallback: (reqestParams) => {
      const { pageRange, mainProductTag, expand, ...reqParams } = reqestParams
      return {
        ...reqParams,
        createTimeStart:
          reqParams.createTimeStart && reqParams.createTimeStart.length === 2 ? reqParams.createTimeStart[0] : null,
        createTimeEnd:
          reqParams.createTimeStart && reqParams.createTimeStart.length === 2 ? reqParams.createTimeStart[1] : null,
      }
    },
  })
  useEffect(() => {
    handleCacheData()
    handleOperateItems()
  }, [])
  const handleOperateItems = () => {
    const items = [] as IMenuItem[]
    const defPer = [
      // { label: '汇报成品坯布', key: 'GreyclothReportFinished' },
      {
        label: <span style={{ color: 'red', fontWeight: 800 }}>成品误汇报-坯布</span>,
        key: 'GreyclothMisReporting',
      },
    ]
    defPer.forEach((item) => {
      if (buttonCodeList.includes(item.key)) {
        items.push(item)
      }
    })
    setoperateItems(items)
  }
  const handleMenuClick = (info: ITableData, items: any) => {
    if (items.key === 'GreyclothReportFinished') {
      onReportNum(info, 1)
    } else if (items.key === 'GreyclothMisReporting') {
      onReportNum(info, 2)
    }
  }
  const handleCacheData = async () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      await form.validateFields()
      search()
      setCachePage({ ...params })
    } else {
      const { SupplierOption, ...resetCacheData } = cacheData
      // 先重置表单再设置缓存！！！
      form.resetFields()
      form.setFieldsValue({
        ...resetCacheData,
      })
      setSupplierOption(SupplierOption || [])
      reload({ ...resetCacheData })
    }
  }
  const onViewLogs = (info: ITableData) => {
    viewLogs(info)
  }
  const onReportNum = (info: ITableData, type: 1 | 2) => {
    reportModalGrey.openModal({ ...info, finishQty: null, type })
  }
  const onUploadFileCancel = () => {
    setimportFileShow(false)
    FormUpload.resetFields()
  }
  const importFileOk = async () => {
    const { file } = await FormUpload.validateFields()
    setuploadLoading(true)
    const res = await importExcelForCreate<{ linkUrl: string }>(file).finally(() => {
      setuploadLoading(false)
      FormUpload.resetFields()
    })
    if (res.code === 200) {
      importNotification(res?.data?.linkUrl)
      search()
      onUploadFileCancel()
    }
  }
  const onEdit = (info: ITableData, type: 1 | 2 | 3 | 4) => {
    editModalGrey.openModal({ ...info, type })
  }
  const getStock = async () => {
    const { fabricCode, fabricSupplierCode } = transferModal.form.getFieldsValue()
    if (!fabricCode || !fabricSupplierCode) return
    const res = await getTransferFabricStock<{ baseFabricStockQty: number; colorFabricStockQty: number }>({
      fabricCode,
      fabricSupplierCode,
    })
    if (res.code == 200) {
      setstockQty({
        baseFabricStockQty: res?.data?.baseFabricStockQty || 0,
        colorFabricStockQty: res?.data?.colorFabricStockQty || 0,
      })
    } else {
      setstockQty({
        baseFabricStockQty: 0,
        colorFabricStockQty: 0,
      })
    }
  }
  return (
    <PageContainer className="fabric_greycloth_wrap">
      <SearchForm
        loading={tableProps.loading}
        form={form}
        searchConfig={searchConfig({
          SupplierOption,
          handleSearchSupplier,
          ProDevSeason,
          form,
        })}
        onFinish={async () => {
          setCachePage({
            ...form.getFieldsValue(),
            SupplierOption,
            current: 1,
            size: params.size,
          })
          search()
        }}
        onReset={() => {
          reset()
          setCachePage({
            current: 1,
            size: 10,
            createTimeStart: defaultDateRange,
          })
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                permission="GreyclothBatchImport"
                type="primary"
                onClick={() => {
                  addModal.openModal()
                }}
                icon={<PlusOutlined />}
                disabled={tableProps.loading}
              >
                新建坯布需求
              </PermissionButton>
              <PermissionButton
                permission="GreyclothBatchImport"
                type="primary"
                onClick={() => {
                  setimportFileShow(true)
                }}
                icon={<ImportOutlined />}
                disabled={tableProps.loading}
              >
                批量新建坯布需求
              </PermissionButton>
              <PermissionButton
                permission="GreyclothInventoryTransfer"
                type="primary"
                onClick={() => {
                  setstockQty({
                    baseFabricStockQty: 0,
                    colorFabricStockQty: 0,
                  })
                  transferModal.openModal()
                }}
                disabled={tableProps.loading}
              >
                面料库存转移
              </PermissionButton>
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="GreyclothExport"
                icon={<UploadOutlined />}
                loading={uploadLoading}
                disabled={tableProps.loading}
                onClick={async () => {
                  const paramsData: Record<string, any> = {}
                  Object.assign(paramsData, params)
                  setuploadLoading(true)
                  setspinning(true)
                  const res = await exportSupplierGreyFabric(paramsData)
                    .catch(() => setspinning(false))
                    .finally(() => {
                      setuploadLoading(false)
                    })
                  if (res?.code === 200 && res?.data) {
                    await exportNotification(res?.data, navigate).finally(() => setspinning(false))
                  }
                }}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        stripe={false}
        isAutoScrollY
        {...tableProps}
        columns={useIndexColumns({
          isRoot,
          onEdit,
          GreyclothEditFabricUnitPrice: buttonCodeList.includes('GreyclothEditFabricUnitPrice'),
          GreyclothEditOrderQty: buttonCodeList.includes('GreyclothEditOrderQty'),
          GreyclothEditRemark: buttonCodeList.includes('GreyclothEditRemark'),
          GreyclothEditQcReport: buttonCodeList.includes('GreyclothEditQcReport'),
          operateItems,
          handleMenuClick,
          onViewLogs,
        })}
        rowKey={(rows) => rows?.id}
      ></CustomTable>
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
      <ImportFileModal
        loading={uploadLoading}
        open={importFileShow}
        onCancel={onUploadFileCancel}
        onOk={importFileOk}
        form={FormUpload}
        tempCode={IMPORT_FILE_ENUM.BATCH_CREATE_FARBRIC_GREYCLOTH}
      ></ImportFileModal>
      <Modal
        title={
          reportModalGrey.currentRecord?.type == 1
            ? '汇报成品坯布'
            : reportModalGrey.currentRecord?.type == 2
            ? '成品误汇报-坯布'
            : null
        }
        open={reportModalGrey.open}
        maskClosable
        onCancel={reportModalGrey.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={reportModalGrey.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={reportModalGrey.confirmLoading}
                onClick={() => {
                  if (reportModalGrey.currentRecord?.type == 1) {
                    reportModalGrey.handleSubmit((vals) =>
                      reportFinishedQuantity({
                        ...vals,
                        id: reportModalGrey.currentRecord?.id || null,
                        supplierCode: reportModalGrey.currentRecord?.supplierCode || null,
                        fabricCode: reportModalGrey.currentRecord?.fabricCode || null,
                      }),
                    )
                  } else if (reportModalGrey.currentRecord?.type == 2) {
                    reportModalGrey.handleSubmit((vals) =>
                      misreportingFinishedQuantity({
                        ...vals,
                        id: reportModalGrey.currentRecord?.id || null,
                        supplierCode: reportModalGrey.currentRecord?.supplierCode || null,
                        fabricCode: reportModalGrey.currentRecord?.fabricCode || null,
                      }),
                    )
                  }
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={[
            {
              name: 'finishQty',
              label: reportModalGrey.currentRecord?.type == 1 ? '成品坯布' : '误汇报数量',
              type: 'InputNumber',
              placeholder: '请输入' + (reportModalGrey.currentRecord?.type == 1 ? '成品坯布' : '误汇报数量'),
              config: {
                precision: 2,
                min: 0,
              },
              rules: [
                {
                  required: true,
                  message: '请输入' + (reportModalGrey.currentRecord?.type == 1 ? '成品坯布' : '误汇报数量'),
                },
              ],
            },
            {
              name: 'flowRemark',
              label: '流水备注',
              type: 'TextArea',
              placeholder: '请输入流水备注',
              config: {
                rows: 3,
              },
              rules: [
                {
                  required: true,
                  message: '请输入流水备注',
                },
              ],
              hidden: reportModalGrey.currentRecord?.type != 2,
            },
          ]}
          form={reportModalGrey.form}
        />
      </Modal>
      <Modal
        title={
          editModalGrey.currentRecord?.type == 1
            ? '面料单价'
            : editModalGrey.currentRecord?.type == 2
            ? '坯布下单量'
            : editModalGrey.currentRecord?.type == 3
            ? '备注'
            : editModalGrey.currentRecord?.type == 4
            ? '编辑质检报告'
            : null
        }
        open={editModalGrey.open}
        maskClosable
        onCancel={editModalGrey.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={editModalGrey.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={editModalGrey.confirmLoading}
                onClick={() => {
                  editModalGrey.handleSubmit((vals) =>
                    editSupplierGreyFabric({
                      ...vals,
                      id: editModalGrey.currentRecord?.id || null,
                    }),
                  )
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={[
            {
              name: 'fabricUnitPrice',
              label: '面料单价',
              type: 'InputNumber',
              placeholder: '请输入面料单价',
              config: {
                precision: 2,
                min: 0,
              },
              rules: [
                {
                  required: true,
                  message: '请输入面料单价',
                },
              ],
              hidden: editModalGrey.currentRecord?.type != 1,
            },
            {
              name: 'orderQty',
              label: '坯布下单量',
              type: 'InputNumber',
              placeholder: '请输入坯布下单量',
              config: {
                precision: 2,
                min: 0,
              },
              rules: [
                {
                  required: true,
                  message: '请输入坯布下单量',
                },
              ],
              hidden: editModalGrey.currentRecord?.type != 2,
            },
            {
              name: 'remark',
              label: '备注',
              type: 'TextArea',
              placeholder: '请输入备注',
              config: {
                rows: 2,
              },
              rules: [
                {
                  required: true,
                  message: '请输入备注',
                },
              ],
              hidden: editModalGrey.currentRecord?.type != 3,
            },
            {
              name: 'qcReport',
              label: '质检报告',
              type: 'UploadFile',
              placeholder: '请上传质检报告',
              config: {
                max: 1,
              },
              rules: [
                {
                  required: true,
                  message: '请上传质检报告',
                },
              ],
              hidden: editModalGrey.currentRecord?.type != 4,
            },
          ]}
          form={editModalGrey.form}
        />
      </Modal>
      <Modal
        title="面料库存转移"
        open={transferModal.open}
        maskClosable
        onCancel={transferModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={transferModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={transferModal.confirmLoading}
                onClick={() => {
                  transferModal.handleSubmit(transferFabricStock)
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <Form
          form={transferModal.form}
          labelCol={{ span: 24 }}
          wrapperCol={{ span: 24 }}
          layout="vertical"
          onValuesChange={(changedValues) =>
            onValuesChange(changedValues, ['fabricCode', 'transferFabricCode'], transferModal.form)
          }
        >
          <Form.Item
            name="fabricCode"
            label="转出面料编码"
            rules={[
              {
                required: true,
                message: '请输入转出面料编码',
              },
            ]}
          >
            <Input placeholder="请输入转出面料编码" onChange={getStock}></Input>
          </Form.Item>
          <Form.Item
            name="fabricSupplierCode"
            label="面料供应商"
            rules={[
              {
                required: true,
                message: '请选择面料供应商',
              },
            ]}
          >
            <Select
              options={SupplierOptionF}
              suffixIcon={null}
              showSearch
              optionFilterProp="label"
              filterOption={false}
              onSearch={handleSearchSupplierF}
              notFoundContent={<Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />}
              placeholder="请选择面料供应商"
              onChange={getStock}
            ></Select>
          </Form.Item>
          <div style={{ color: 'var(--color-text-4)', marginBottom: 12 }}>
            <div>坯布库存总数：{stockQty?.baseFabricStockQty}</div>
            <div>色布库存总数： {stockQty?.colorFabricStockQty}</div>
          </div>
          <Form.Item
            name="transferFabricCode"
            label="转入面料编码"
            rules={[
              {
                required: true,
                message: '请输入转入面料编码',
              },
            ]}
          >
            <Input placeholder="请输入转入面料编码"></Input>
          </Form.Item>
          <Form.Item name="flowRemark" label="流水备注">
            <Input.TextArea rows={3} placeholder="请输入流水备注"></Input.TextArea>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        width={800}
        title="新建坯布需求"
        open={addModal.open}
        maskClosable
        onCancel={addModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={addModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={addModal.confirmLoading}
                onClick={() => {
                  addModal.handleSubmit((vals) =>
                    createSupplierGreyFabric({
                      ...vals,
                      seasonName: ProDevSeason?.find((item) => item.value == vals.seasonId)?.label,
                      supplierId: SupplierOptionF?.find((item) => item.value == vals.supplierCode)?.id,
                      supplierName: SupplierOptionF?.find((item) => item.value == vals.supplierCode)?.supplierName,
                    }),
                  )
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div className="greycloth_addmodal">
          <EditFormVertical
            editConfig={[
              {
                label: '开发季',
                name: 'seasonId',
                type: 'Select',
                option: ProDevSeason,
                config: {
                  onChange: (_: any, items: any) => {
                    handleSearchFabric('', items?.label)
                    addModal?.form?.setFieldsValue({
                      fabricCode: null,
                      supplierCode: null,
                    })
                    setSupplierIds([])
                  },
                },
                rules: [
                  {
                    required: true,
                    message: '请选择开发季',
                  },
                ],
              },
              {
                name: 'fabricCode',
                label: '面料',
                type: 'Select',
                option: FabricOption,
                placeholder: '请选择面料',
                config: {
                  showSearch: true,
                  optionFilterProp: 'label',
                  filterOption: false,
                  onSearch: (val: string) =>
                    handleSearchFabric(
                      val,
                      ProDevSeason?.find((item) => item?.seasonId == addModal.form?.getFieldValue('seasonId'))?.label,
                    ),
                  onChange: (_: any, items: any) => {
                    setSupplierIds(items?.supplierIds || [])
                    handleSearchSupplierF('', items?.supplierIds)
                    addModal?.form?.setFieldsValue({
                      supplierCode: null,
                    })
                  },
                },
                rules: [
                  {
                    required: true,
                    message: '请选择面料',
                  },
                ],
              },
              {
                label: '面料单位',
                name: 'fabricUnit',
                type: 'Select',
                placeholder: '请选择面料单位',
                option: [
                  { label: '千克', value: 'kg' },
                  { label: '米', value: 'm' },
                ],
                config: {
                  showSearch: true,
                  optionFilterProp: 'label',
                },
                rules: [
                  {
                    required: true,
                    message: '请选择面料单位',
                  },
                ],
              },
              {
                name: 'supplierCode',
                label: '面料供应商',
                type: 'Select',
                option: SupplierOptionF,
                config: {
                  suffixIcon: null,
                  showSearch: true,
                  optionFilterProp: 'label',
                  filterOption: false,
                  onSearch: (newVal: string) => handleSearchSupplierF(newVal, SupplierIds),
                  notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
                },
                rules: [
                  {
                    required: true,
                    message: '请选择面料供应商',
                  },
                ],
              },
              {
                name: 'orderQty',
                label: '坯布下单量',
                type: 'InputNumber',
                placeholder: '请输入坯布下单量',
                config: {
                  precision: 2,
                  min: 0,
                },
                rules: [
                  {
                    required: true,
                    message: '请输入坯布下单量',
                  },
                ],
              },
              {
                name: 'fabricUnitPrice',
                label: '面料单价',
                type: 'InputNumber',
                placeholder: '请输入面料单价',
                config: {
                  precision: 2,
                  min: 0,
                },
                rules: [
                  {
                    required: true,
                    message: '请输入面料单价',
                  },
                ],
              },

              {
                name: 'remark',
                label: '备注',
                type: 'TextArea',
                placeholder: '请输入备注',
                config: {
                  rows: 2,
                },
              },
            ]}
            form={addModal.form}
          />
        </div>
      </Modal>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
